package com.mj.mybatis;

import com.mj.dao.IUserMapper;

import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

/**
 * @author 马洁
 * @date 2020/9/18 - 11:18
 */
public class MySqlSessionImpl implements MySqlSession {
    private Connection connection;
    private Map<Class<?>, Object> mapper;

    public MySqlSessionImpl(Connection connection, Map<String, SqlBean> mapper) {
        this.connection = connection;
    }

    @Override
    public IUserMapper getMapper(Class<IUserMapper> iUserMapperClass) {
        Object object = mapper.get(iUserMapperClass);

        if (object == null) {
            object = createProxyClassOfObjectByInterface(iUserMapperClass);
            mapper.put(iUserMapperClass, object);
        }

        return (IUserMapper) object;
    }

    private Object createProxyClassOfObjectByInterface(Class<IUserMapper> iUserMapperClass) {
        return Proxy.newProxyInstance(iUserMapperClass.getClassLoader(), new Class[]{iUserMapperClass},
                new MyBatisInvocationHandlerImpl(connection));
    }

    @Override
    public void close() {
        try {
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Connection connection = null;
        // MySqlSessionImpl mySqlSession = new MySqlSessionImpl(connection);
        // IUserMapper object = (IUserMapper) mySqlSession.createProxyClassOfObjectByInterface(IUserMapper.class);
        // System.out.println(object.findAll());
    }
}
